import { io } from 'socket.io-client'
import axios from 'axios'
import { useScanStore } from '@renderer/store/pinia/scan'
import { useGlobalLoading } from '@renderer/utils/hooks/useGlobalLoading'
import { useImageStore } from '@renderer/store/pinia/image'
import { BaseScanSeries } from '@renderer/views/multiScanSeriesPage/types'

const throughGatewayFlag = false
const uri = throughGatewayFlag ? 'http://localhost:9002' : 'http://127.0.0.1:8080'
const ioInstance = io(uri + '/ct', {
  autoConnect: true
})
const { showLoading, hideLoading } = useGlobalLoading()
ioInstance.on('connect', () => {
  console.log('io connected')
})


ioInstance.on('image', (data) => {
  const imageStore = useImageStore()
  const scanStore = useScanStore()
  if (data?.stack) {
    const imageId = data.stack.image_id
    const seriesId = scanStore.scanSeriesInfo.imageId2seriesIdMap.get(imageId)
    const series = scanStore.scanSeriesInfo.getSeriesById(seriesId)
    if (series) {
      series.receiveScoutImage()
    }
    console.log('收到image,时间是：', data.stack.image_id, seriesId)
    imageStore.setImageInfo(imageId, {
      imgSrc: data.stack.img,
      fourCornerInfo: data.stack.info_layer,
      sliceInfo: data.stack.slice_info,
      phaseInfo: data.stack.phase_info
    })
  }
})


function sendIoMsg(msg) {
  if (throughGatewayFlag) {
    const msgBody = {
      systemType: 'image',
      ...msg
    }
    console.log('发送获取image消息', JSON.stringify(msg))
    ioInstance.emit('fe_gateway', JSON.stringify(msgBody))
  } else {
    ioInstance.send({
      ...msg,
      imageId: getActiveImageId()
    })
  }
}

function getActiveImageId() {
  const scanStore = useScanStore()
  return scanStore.scanSeriesInfo.getActiveImageId()
}


function getProvider() {
  return {
    throughGatewayFlag,
    baseUri: throughGatewayFlag ? 'http://localhost:9000' : 'http://127.0.0.1:8080',
    sendMsg: sendIoMsg,
    ioInstance: ioInstance
  }

}

export {
  getProvider
}

